
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;
layui.use(['tableEdit',"excel","selectInput"], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer,
        excel = layui.excel,
        selectInput = layui.selectInput;

    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    function getAllJson(jsons) {
        let tmpitem = []
        for (let item of jsons) {
            let tmparr = {}
            tmparr["value"] = item["code"];
            tmparr["name"] = item["name"];
            if (item["users"]) {
                for (let it of item["users"]) {
                    item["list"].push(it)
                }
            }
            if (item["list"] && item["list"].length) {
                tmparr["children"] = getAllJson(item["list"]);
                tmpitem.push(tmparr)
            } else {
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }

    function getxmselect(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }

    let customerTypes=[];
    let salesmanList=[];
    let levels=[];
    let sourceOfCustomers=[];
    layer.ready(function () {
        //客户名称
        setCustomerInfo("");

        //客户类型
        let customerTypeData = getdictionary(6, 27);
        let customerTypeList = [];
        for(let i in customerTypeData){
            let customerTypeTemp = {
                name: customerTypeData[i].name,
                value: customerTypeData[i].code
            }
            customerTypeList.push(customerTypeTemp);
        }
        customerTypes=getxmselect("#customerType", "customerType", customerTypeList);


        //获取当前用户的部门及人员结构树，业务员名称
        let treeList = getCurrentDepartmentUser();
        if (treeList && treeList.list) {
            let userTree = getAllJson(treeList.list);
            salesmanList=getxmselect("#salesmanCode","salesmanCode", userTree);
        } else {
            salesmanList=getxmselect("#salesmanCode","salesmanCode", [{name: user.name, value: user.code}]);
        }


        //客户等级
        let levelData=getdictionary(6,26);
        let levelList=[];
        for(let i in levelData){
            let levelTemp = {
                name: levelData[i].name,
                value: levelData[i].code
            }
            levelList.push(levelTemp);
        }
        levels=getxmselect("#level", "level", levelList);

        //客户来源
        let sourceOfCustomerData=getdictionary(1,3);
        let sourceOfCustomerList=[];
        for(let i in sourceOfCustomerData){
            let sourceOfCustomerTemp = {
                name: sourceOfCustomerData[i].name,
                value: sourceOfCustomerData[i].code
            }
            sourceOfCustomerList.push(sourceOfCustomerTemp);
        }
        sourceOfCustomers=getxmselect("#sourceOfCustomer", "sourceOfCustomer", sourceOfCustomerList);


    });

    function setCustomerInfo(initData) {
        //客户名称
        let ins = selectInput.render({
            elem: '#customerSelect',
            name: 'customerSelect',
            initValue: initData,
            hasSelectIcon: true,
            placeholder: '请输入名称',
            data: [],
        })
        //监听输入
        ins.on('itemInput(customerSelect)', function (obj) {
            let tempData = [];
            $.ajax({
                url: "basicInformation/getCustomerInfo?info=" + obj.value,
                async: false,
                success: function (res) {
                    if (res.status == 200) {
                        let customerInfo = res.data.customerInfo;
                        for (let i in customerInfo) {
                            customerInfo[i]["value"] = customerInfo[i].code;
                            tempData.push(customerInfo[i]);
                        }
                    }
                }
            })
            ins.addSelect(tempData)
        })

        // 监听select 选择事件
        ins.on('itemSelect(customerSelect)', function (obj) {
            let code = obj.data;
            $("#customerCode").val(code);
        });
    }



    form.render();//表单刷新

    let initData = [];
    table.render({
        elem: '#collectionSelect',
        data:initData,
        toolbar: '#collectionToolbar',
        totalRow: true,
        cols: [[
            {field: 'numbers',type:'numbers',title:'序号', totalRowText: '合计'},
            {field: 'customerName', title: '客户名称',width:200, align: 'center'},
            {field: 'customerType', title: '客户类型',width:200, align: 'center'},
            {field: 'levelName', title: '客户等级',width:200, align: 'center'},
            {field: 'sourceOfCustomers', title: '客户来源',width:200, align: 'center'},
            {field: 'attributesOfCustomers', title: '客户属性' ,width: 200},
            {field: 'abbreviation', title: '客户简称',width:200, align: 'center'},
            {field: 'customerCode', title: '客户编码',width:200, align: 'center'},
            {field: 'shortCode', title:'客户三位简码',width:200, sort: true, align: 'center'},
            {field: 'createDateStr', title:'创建日期',width:200, sort: true, align: 'center'},
            {field: 'payday', title:'账期', sort: true,width:200, align: 'center'},

            {field: 'carryProductNum', title:'出运数量',width:200, align: 'center', totalRow: true},
            {field: 'shipmentAmount', title:'出货金额',width:200, align: 'center', totalRow: true},
            {field: 'billExchangeInfoNum', title:'结汇数量',width:200, align: 'center', totalRow: true},
            {field: 'billExchangeInfoAmount', title:'结汇金额',width:200, align: 'center', totalRow: true},
        ]],
        id: 'collectionTableId',
        height: $(document).height() - $('#collectionSelect').offset().top - 75,
        //开启分页
        page: true,
        limits: [300, 600, 900]
    });


    form.on('submit(submitform)', function (data) {
        table.reload('collectionTableId', {
            page: {
                limit:300,
                curr: 1
            },
            url: 'customer/customerOrderAndShipInfoListByPage',
            where: data.field,
        }, 'data');
        return false;
    });

    form.on('submit(exportData)', function (queryReq) {
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        $.ajax({
            data: queryReq.field,
            url:"customer/customerOrderAndShipInfoExport",
            success: function(res) {
                if(res.status == 200){
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 120,
                        'X': 120
                    }, 80);
                    excel.exportExcel({
                        sheet1: res.data.data
                    }, '客户下单出货记录.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });

    /**清空监听  **/
    $("#clear").on("click", function() {
        $("#customerCode").val('');
        customerTypes.setValue([]);
        salesmanList.setValue([]);
        sourceOfCustomers.setValue([]);
        levels.setValue([]);
    });
});